import axios from 'axios';
import { ElMessage } from 'element-plus';
import { startLoading, stopLoading } from '../loading'; // 引入 loading 管理函数
import { useRoute, useRouter } from 'vue-router';


const router = useRouter();
const axiosInstance = axios.create({
	baseURL: '',
	timeout: 30000 // 请求超时时间
});

// const loadingInstance = ref(null)

// 添加请求拦截器
axiosInstance.interceptors.request.use(
	(config: any) => {
		startLoading(); // 显示加载遮罩
		const token = localStorage.getItem('token');
		const tokenUserId = localStorage.getItem('tokenUserId');
		config.headers.BearerToken = token ? `${token}` : undefined;
		config.headers.userId = tokenUserId ? `${tokenUserId}` : undefined;

		return config;
	},
	(error: any) => {
		stopLoading(); // 隐藏加载遮罩
		return Promise.reject(error);
	}
);

// 添加响应拦截器
axiosInstance.interceptors.response.use(
	(response) => {
		stopLoading(); // 隐藏加载遮罩
		// if (loadingInstance) {
		//   loadingInstance.close();
		// }
		switch (response.data.code) {
			case 0:
				ElMessage({
					message: response.data.msg || '操作成功',
					type: 'success'
				});

				return Promise.reject(response.data);

			case 400:
				ElMessage({
					message: response.data.message || '业务数据异常',
					type: 'error'
				});

				return Promise.reject(response.data);

			case 200:
				if (response.data.result === false) {
					ElMessage({
						message: response.data.message || '业务数据异常',
						type: 'error'
					});
					return Promise.reject(response.data);
				}
				return response.data;
			case 401:
				localStorage.clear();
				ElMessage({
					message: '登录状态发生变化，请重新登录',
					type: 'error',
					duration: 1000 // 设置消息显示时间为1秒
				});
				setTimeout(() => {
					window.location.href = '/home/login';
				}, 1000);
				return Promise.reject(response.data);

			default:
				ElMessage({
					message: response.data.message || '业务数据异常',
					type: 'error'
				});
				return Promise.reject(response.data);
		}
	},
	(error) => {
		stopLoading(); // 隐藏加载遮罩
		switch (error.response.status) {
			// case 401:
			// 	localStorage.clear();
			// 	ElMessage({
			// 		message: '登录状态发生变化，请重新登录',
			// 		type: 'error',
			// 		duration: 1000 // 设置消息显示时间为1秒
			// 	});
			// 	setTimeout(() => {
			// 		window.location.href = '/home/login';
			// 	}, 1000);
			// 	break;
			case 404:
				ElMessage({
					message: '404',
					type: 'error'
				});
				break;
			case 500:
				ElMessage({
					message: '服务器内部错误',
					type: 'error'
				});

				break;
			case 502:
				ElMessage({
					message: '网关错误:502',
					type: 'error'
				});

				break;
			default:
				ElMessage({
					message: error.response.data.message,
					type: 'error'
				});
				break;
		}
		return Promise.reject(error);
	}
);

export default axiosInstance;
